package com.ruoyi.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.core.IJPayHttpResponse;
import com.ijpay.core.enums.RequestMethod;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.IpKit;
import com.ijpay.core.kit.PayKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.unionpay.UnionPayApi;
import com.ijpay.unionpay.enums.ServiceEnum;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.enums.WxApiType;
import com.ijpay.wxpay.enums.WxDomain;
import com.ijpay.wxpay.model.v3.Amount;
import com.ijpay.wxpay.model.v3.UnifiedOrderModel;
import com.ruoyi.business.app.vo.AppPurchaseVo;
import com.ruoyi.business.app.vo.AppUserCouponVo;
import com.ruoyi.business.bo.HcxCarWashAddBo;
import com.ruoyi.business.bo.HcxCarWashEditBo;
import com.ruoyi.business.bo.HcxCarWashQueryBo;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.enums.DetailedTypeEnum;
import com.ruoyi.business.enums.VipFlagEnum;
import com.ruoyi.business.mapper.*;
import com.ruoyi.business.service.IHcxCarWashService;
import com.ruoyi.business.vo.HcxCarWashVo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.vo.ObsUploadRespVo;
import com.ruoyi.common.utils.AssertUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.oss.OssUtils;
import com.ruoyi.common.utils.qrcode.QRCodeUtil;
import com.ruoyi.pay.entity.AliPayBean;
import com.ruoyi.pay.entity.UnionPayBean;
import com.ruoyi.pay.entity.WxPayV3Bean;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.security.cert.X509Certificate;
import java.util.*;

/**
 * 洗车卡设置Service业务层处理
 *
 * @author wsdz
 * @date 2022-08-17
 */
@Service
@AllArgsConstructor
@Slf4j
public class HcxCarWashServiceImpl extends ServicePlusImpl<HcxCarWashMapper, HcxCarWash> implements IHcxCarWashService {


    private final HcxUserCouponMapper hcxUserCouponMapper;


    private final HcxAppUserMapper hcxAppUserMapper;


    private final HcxWithdrawDetailMapper hcxWithdrawDetailMapper;

    private final RedisCache redisCache;

    private final OssUtils ossUtils;

    private final WxPayV3Bean wxPayV3Bean;

    private final AliPayBean aliPayBean;

    private final UnionPayBean unionPayBean;

    private final HcxMerchantOrderMapper hcxMerchantOrderMapper;

    private final HcxWithdrawDetailMapper withdrawDetailMapper;

    private final HcxPlatformProfitMapper hcxPlatformProfitMapper;

    private final HcxPlatformUserMapper hcxPlatformUserMapper;


    @Override
    public HcxCarWashVo queryById(Long id) {
        return getVoById(id, HcxCarWashVo.class);
    }

    @Override
    public TableDataInfo<HcxCarWashVo> queryPageList(HcxCarWashQueryBo bo) {
        PagePlus<HcxCarWash, HcxCarWashVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), HcxCarWashVo.class);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<HcxCarWashVo> queryList(HcxCarWashQueryBo bo) {
        return listVo(buildQueryWrapper(bo), HcxCarWashVo.class);
    }

    private LambdaQueryWrapper<HcxCarWash> buildQueryWrapper(HcxCarWashQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HcxCarWash> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCarPrice() != null, HcxCarWash::getCarPrice, bo.getCarPrice());
        lqw.eq(bo.getWashTimes() != null, HcxCarWash::getWashTimes, bo.getWashTimes());
        lqw.eq(StrUtil.isNotBlank(bo.getDelFlag()), HcxCarWash::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    @Override
    public Boolean insertByAddBo(HcxCarWashAddBo bo) {
        HcxCarWash add = BeanUtil.toBean(bo, HcxCarWash.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(HcxCarWashEditBo bo) {
        HcxCarWash update = BeanUtil.toBean(bo, HcxCarWash.class);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(HcxCarWash entity) {
        HcxCarWash hcxCarWash = getBaseMapper().selectOne(null);
        AssertUtils.isTrue(ObjectUtil.isNotEmpty(hcxCarWash), "已存在洗车卡,不能重复添加");
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    @Override
    public String importHcxCarWash(List<HcxCarWashVo> hcxCarWashList) {
        AssertUtils.isTrue(CollectionUtils.isNotEmpty(hcxCarWashList), "导入数据不能为空");
        int successNum = 0;
        for (HcxCarWashVo hcxCarWash : hcxCarWashList) {
            HcxCarWash add = BeanUtil.toBean(hcxCarWash, HcxCarWash.class);
            save(add);
            successNum++;
        }
        String msg = String.format("导入完成，共计 %d 条数据，成功 %d 条！", hcxCarWashList.size(), successNum);
        if (successNum != hcxCarWashList.size()) {
            msg = msg + String.format("失败 %d 条！", hcxCarWashList.size() - successNum);
        }
        return msg;
    }


    @Override
    public AppUserCouponVo queryUserCoupon(Long carWashId) {
        AppUserCouponVo appUserCouponVo = new AppUserCouponVo();
        HcxCarWash carWash = getById(carWashId);
        // 查询用户所拥有的符合条件的优惠券 筛选条件为 (1 未使用  2 未过期(当前时间在优惠券开始和结束时间之内) 3 订单金额满足优惠券的满减金额)
        // 假设洗车卡价格103    用户有两张面额20、30的优惠券都满足要求   面额20(满100元可用)   面额30(满100元可用)  则优先使用这个30面额大的优惠券

        List<HcxUserCoupon> list = hcxUserCouponMapper.selectList(new LambdaQueryWrapper<HcxUserCoupon>()
                .eq(HcxUserCoupon::getUserId, SecurityUtils.getUserId())
                .apply("curdate() >= begin_date")
                .apply("curdate() <= end_date ")
                .le(HcxUserCoupon::getConditionPrice, carWash.getCarPrice())
                .eq(HcxUserCoupon::getStatus, Constants.ZERO).orderByDesc(HcxUserCoupon::getDenomination));

        List<AppUserCouponVo> result = new ArrayList<>();
        for (HcxUserCoupon hcxUserCoupon : list) {
            AppUserCouponVo userCouponVo = new AppUserCouponVo();

            userCouponVo.setId(hcxUserCoupon.getId());
            userCouponVo.setDenomination(hcxUserCoupon.getDenomination());

            result.add(userCouponVo);
        }

        if (CollectionUtil.isNotEmpty(result)) {
            appUserCouponVo = result.get(0);
        }

        // 订单有效期
        String orderValid = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.HCXORDERVALID);
        appUserCouponVo.setOrderValid(orderValid);

        return appUserCouponVo;
    }

    @Override
    @Transactional
    public AppPurchaseVo purchase(HttpServletRequest request, Long carWashId, Long couponId, String payType) throws Exception {

        AppPurchaseVo appPurchaseVo = new AppPurchaseVo();


        // 查询洗车卡信息
        HcxCarWash carWash = getById(carWashId);
        AssertUtils.isTrue(ObjectUtil.isNotEmpty(carWash), "非法的洗车卡id");

        // 查询用户优惠券信息
        HcxUserCoupon userCoupon = hcxUserCouponMapper.selectById(couponId);


        // 查询当前用户
        HcxAppUser currentUser = hcxAppUserMapper.selectById(SecurityUtils.getUserId());


        // todo 购买下单
        HcxMerchantOrder hcxMerchantOrder = new HcxMerchantOrder();
        hcxMerchantOrder.setCarId(carWashId);

        hcxMerchantOrder.setUserId(SecurityUtils.getUserId());
        // 洗车卡是针对平台的所以没有商家id
        // 应付金额
        hcxMerchantOrder.setShouldPrice(carWash.getCarPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
        // 实付金额= 洗车卡价格-优惠券面额
        if (ObjectUtil.isNotEmpty(userCoupon)) {
            hcxMerchantOrder.setActualPrice(carWash.getCarPrice().subtract(userCoupon.getDenomination()).setScale(2, BigDecimal.ROUND_HALF_UP));
            hcxMerchantOrder.setUserCouponId(couponId);
            hcxMerchantOrder.setDenomination(userCoupon.getDenomination());
            hcxMerchantOrder.setConditionPrice(userCoupon.getConditionPrice());
            hcxMerchantOrder.setUseIntroduce(userCoupon.getUseIntroduce());
        } else {
            // 实付金额=应付金额
            hcxMerchantOrder.setActualPrice(hcxMerchantOrder.getShouldPrice());
        }
        hcxMerchantOrder.setProductId(Long.valueOf(1));
        hcxMerchantOrder.setProductName("洗车卡");
        hcxMerchantOrder.setMerchantName("平台");


        hcxMerchantOrder.setStatus(Constants.ZERO);
        // 洗车次数
        hcxMerchantOrder.setWashTimes(carWash.getWashTimes());
        // 剩余洗车次数
        hcxMerchantOrder.setSurplusTimes(carWash.getWashTimes());
        // 订单类型
        hcxMerchantOrder.setOrderType(Constants.ONE);
        // 支付方式
        hcxMerchantOrder.setPayType(payType);
        // 生成订单编号 如果是单次 则以 YC开头+年月日时分秒毫秒+5位随机数   如果是洗车卡(D代表多次) 则以 DC+年月日时分秒毫秒+5位随机数
        String format = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        String numbers = RandomUtil.randomNumbers(5);
        String orderNum = "DC" + format + numbers;
        hcxMerchantOrder.setOrderNum(orderNum);



        log.info("优惠券id---------》{}", couponId);
        log.info("洗车卡实付金额------》{}", hcxMerchantOrder.getActualPrice());

        // 应付金额转换为分
        int fen = hcxMerchantOrder.getActualPrice().movePointRight(2).intValue();


        int bijiao = hcxMerchantOrder.getActualPrice().compareTo(new BigDecimal(0));

        boolean isFanyong=false;
        // 大于0
        if (bijiao == 1) {
            // 微信支付
            if (Constants.ONE.equals(payType)) {


                UnifiedOrderModel unifiedOrderModel = new UnifiedOrderModel()
                        .setAppid(wxPayV3Bean.getAppId())
                        .setMchid(wxPayV3Bean.getMchId())
                        .setDescription("购买洗车卡会员")
                        .setOut_trade_no(orderNum)
                        .setAttach("微信支付方式支付")
                        .setNotify_url(wxPayV3Bean.getDomain().concat(wxPayV3Bean.getNotifyUrl()))
                        .setAmount(new Amount().setTotal(fen));

                log.info("统一下单参数 {}", JSONUtil.toJsonStr(unifiedOrderModel));
                IJPayHttpResponse response = WxPayApi.v3(
                        RequestMethod.POST,
                        WxDomain.CHINA.toString(),
                        WxApiType.APP_PAY.toString(),
                        wxPayV3Bean.getMchId(),
                        getSerialNumber(),
                        getPlatSerialNumber(),
                        wxPayV3Bean.getKeyPath(),
                        JSONUtil.toJsonStr(unifiedOrderModel)
                );
                log.info("统一下单响应 {}", response);
                // 根据证书序列号查询对应的证书来验证签名结果
                boolean verifySignature = WxPayKit.verifySignature(response, wxPayV3Bean.getPlatformCertPath());
                if (verifySignature) {
                    JSONObject entries = JSONUtil.parseObj(response.getBody());
                    String prepayId = entries.getStr("prepay_id");
                    log.info("预支付的id为--------》{}", prepayId);
                    Map<String, String> orderMap = WxPayKit.appCreateSign(wxPayV3Bean.getAppId(), wxPayV3Bean.getMchId(), prepayId, wxPayV3Bean.getKeyPath());
                    appPurchaseVo.setOrderInfo(orderMap);
                }
                // todo 相关业务处理在回调中处理
            } else if (Constants.TWO.equals(payType)) {
                // 支付宝支付

                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                model.setBody("支付宝支付");
                model.setSubject("购买洗车卡会员");
                model.setOutTradeNo(orderNum);
                model.setTotalAmount(hcxMerchantOrder.getActualPrice().toString());
                String orderInfo = AliPayApi.appPayToResponse(model, aliPayBean.getDomain() + aliPayBean.getNotifyUrl()).getBody();

                log.info("支付宝下单 {}", orderInfo);
                Map<String, String> orderMap = new HashMap<>();
                orderMap.put("orderInfo", orderInfo);
                appPurchaseVo.setOrderInfo(orderMap);

                // todo 相关业务处理在回调中处理


            } else if (Constants.THREE.equals(payType)) {
                // 银联支付

                String notifyUrl = unionPayBean.getDomain().concat("/unionPay/payNotify");

                String ip = IpKit.getRealIp(request);
                if (StrUtil.isBlank(ip)) {
                    ip = "127.0.0.1";
                }

                Map<String, String> params = com.ijpay.unionpay.model.UnifiedOrderModel.builder()
                        .service(ServiceEnum.NATIVE.toString())
                        .mch_id(unionPayBean.getMachId())
                        .out_trade_no(WxPayKit.generateStr())
                        .body("IJPay 云闪付-扫码支付")
                        .attach("聚合支付 SDK")
                        .total_fee(String.valueOf(fen))
                        .mch_create_ip(ip)
                        .notify_url(notifyUrl)
                        .nonce_str(WxPayKit.generateStr())
                        .build()
                        .createSign(unionPayBean.getKey(), SignType.MD5);

                String xmlResult = UnionPayApi.execution(unionPayBean.getServerUrl(), params);
                log.info("xmlResult:" + xmlResult);
                Map<String, String> result = WxPayKit.xmlToMap(xmlResult);

                // todo 相关业务处理在回调中处理

            } else {
                // 如果是余额支付
                AssertUtils.isTrue(currentUser.getBalancePrice().compareTo(carWash.getCarPrice()) != -1, "余额不足");
                // 金额-订单实付金额
                currentUser.setBalancePrice(currentUser.getBalancePrice().subtract(hcxMerchantOrder.getActualPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));

                // 订单状态修改为已支付
                hcxMerchantOrder.setStatus(Constants.ONE);

                // 当前登录用户修改为vip
                currentUser.setVipFlag(Constants.ONE);

                // vip到期时间
                currentUser.setVipTime(DateUtils.addDays(new Date(), carWash.getValidDay()));


                hcxAppUserMapper.updateById(currentUser);

                // 优惠券状态改为已使用
                if (ObjectUtil.isNotEmpty(userCoupon)) {
                    userCoupon.setStatus(Constants.ONE);
                    hcxUserCouponMapper.updateById(userCoupon);
                }

                isFanyong=true;

            }
        } else {
            // 如果 小于等于0

            // 订单状态修改为已支付
            hcxMerchantOrder.setStatus(Constants.ONE);

            // 当前登录用户修改为vip
            currentUser.setVipFlag(Constants.ONE);

            hcxAppUserMapper.updateById(currentUser);

            // 优惠券状态改为已使用
            if (ObjectUtil.isNotEmpty(userCoupon)) {
                userCoupon.setStatus(Constants.ONE);
                hcxUserCouponMapper.updateById(userCoupon);
            }

            isFanyong=true;

        }

        // 设置logo小图标
        String logoAddress = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.QRCODE_LOGO_ADDRESS);
        AssertUtils.isNotBlank(logoAddress, "logo地址还没有配置,请后台配置!");
        // 分享二维码存放目录
        String destPath = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.QRCODE_DESC_ADDRESS);
        AssertUtils.isNotBlank(destPath, "二维码存放地址还没有配置,请后台配置!");


        // 生成二维码
        MultipartFile multipartFile = QRCodeUtil.encode(hcxMerchantOrder.getOrderNum(), logoAddress, destPath, true);
        // 文件上传
        ObsUploadRespVo obsUploadRespVo = ossUtils.uploadMultipartFile(multipartFile);
        hcxMerchantOrder.setQrCode(obsUploadRespVo.getObjectUrl());

        hcxMerchantOrderMapper.insert(hcxMerchantOrder);

        if(isFanyong){
            // 洗车卡返佣
            washCard(currentUser, hcxMerchantOrder);
        }

        appPurchaseVo.setQrCode(obsUploadRespVo.getObjectUrl());

        return appPurchaseVo;
    }
    private String getSerialNumber() {
        // 获取证书序列号
        X509Certificate certificate = PayKit.getCertificate(FileUtil.getInputStream(wxPayV3Bean.getCertPath()));
        String serialNo = certificate.getSerialNumber().toString(16).toUpperCase();
        log.info("证书系列号为--->{}", serialNo);
        return serialNo;
    }

    private String getPlatSerialNumber() {
        // 获取平台证书序列号
        X509Certificate certificate = PayKit.getCertificate(FileUtil.getInputStream(wxPayV3Bean.getPlatformCertPath()));
        String platSerialNo = certificate.getSerialNumber().toString(16).toUpperCase();
        log.info("平台系列号为--->{}", platSerialNo);
        return platSerialNo;
    }


    /**
     * @description: 洗车卡返佣
     **/
    @Override
    public void washCard(HcxAppUser hcxAppUser, HcxMerchantOrder hcxMerchantOrder) {
        log.info("我有可能来自微信{}",hcxMerchantOrder.getId());
        // 返佣层级设置
        String fanyLevel = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.TUIGUANGRENSHU);

        // 处理10块的返佣逻辑
        chuliShi(hcxAppUser, hcxMerchantOrder, 0, fanyLevel);

        // 处理150块的返佣逻辑
        chuliYbw(hcxAppUser,hcxMerchantOrder);
    }


    /**
     * @description:
     * @author: kubilewang
     * @date: 2023/1/14 16:55
     * @param:
     * @param: hcxAppUser
     * @param: hcxMerchantOrder
     * @param: number 递归调用的次数 默认从0开始
     * @Return: void
     **/
    private void chuliShi(HcxAppUser hcxAppUser, HcxMerchantOrder hcxMerchantOrder, int number, String fanyLevel) {
        //和自己同级的人
        List<HcxAppUser> list = hcxAppUserMapper.selectList(
                new LambdaQueryWrapper<HcxAppUser>()
                        .eq(HcxAppUser::getInviteFullCode, hcxAppUser.getInviteFullCode())
                        .eq(HcxAppUser::getVipFlag,VipFlagEnum.ISVIP.getValue())
                        .orderByAsc(HcxAppUser::getVipTime)
        );
        // 判断用户是不是前两个
        int i = list.indexOf(hcxAppUser);
        if (i < 2) {
            // 证明是平台邀请的第一个人
            if ("0".equals(hcxAppUser.getInviteFullCode())) {
                pingtaiShi(hcxMerchantOrder);
                return;
            }
            if (number <= Integer.valueOf(fanyLevel)) {
                // 查找父级的邀请码
                String yaoqingma = hcxAppUser.getInviteFullCode().substring(hcxAppUser.getInviteFullCode().length() - 6);
                HcxAppUser parent = hcxAppUserMapper.selectOne(new LambdaQueryWrapper<HcxAppUser>().eq(HcxAppUser::getInviteCode, yaoqingma));
                // 拿到10块钱
                shikuai(parent, hcxAppUser);
                // 循环一次记录加1
                number++;
                // 递归调用 往上返系统参数里配置的级别
                chuliShi(parent, hcxMerchantOrder, number, fanyLevel);
            }
        }

    }


    /**
     * @description: 处理150的返佣逻辑
     * @author: kubilewang
     * @date: 2023/1/14 16:55
     * @param:
     * @param: hcxAppUser
     * @param: hcxMerchantOrder
     * @param: number 递归调用的次数 默认从0开始
     * @Return: void
     **/
    private void chuliYbw(HcxAppUser hcxAppUser,HcxMerchantOrder hcxMerchantOrder) {
        //和自己同级的人
        List<HcxAppUser> list = hcxAppUserMapper.selectList(
                new LambdaQueryWrapper<HcxAppUser>()
                        .eq(HcxAppUser::getInviteFullCode, hcxAppUser.getInviteFullCode())
                        .eq(HcxAppUser::getVipFlag,VipFlagEnum.ISVIP.getValue())
                        .orderByAsc(HcxAppUser::getVipTime)
        );
        // 判断用户是第三个或者以后的
        int i = list.indexOf(hcxAppUser);
        if (i < 2) {
            // 证明是平台邀请的第一个人
            if ("0".equals(hcxAppUser.getInviteFullCode())) {
                pingtaiYbw(hcxMerchantOrder);
                return;
            }
            // 查找父级的邀请码
            String yaoqingma = hcxAppUser.getInviteFullCode().substring(hcxAppUser.getInviteFullCode().length() - 6);
            HcxAppUser parent = hcxAppUserMapper.selectOne(new LambdaQueryWrapper<HcxAppUser>().eq(HcxAppUser::getInviteCode, yaoqingma));
            chuliYbw(parent,hcxMerchantOrder);
        }else{
            // 查找父级的邀请码
            String yaoqingma = hcxAppUser.getInviteFullCode().substring(hcxAppUser.getInviteFullCode().length() - 6);
            HcxAppUser parent = hcxAppUserMapper.selectOne(new LambdaQueryWrapper<HcxAppUser>().eq(HcxAppUser::getInviteCode, yaoqingma));
            // 拿到150块钱
            yibaiwu(parent, hcxAppUser);
        }
    }

    /**
     * @description: 150的分佣
     * @author: kubilewang
     * @param:
     * @param: hcxAppUser
     * @param: shareUser
     * @Return: void
     **/
    private void yibaiwu(HcxAppUser hcxAppUser, HcxAppUser shareUser) {

        // 判斷用戶是不是Vip并且在有效期内
        if (hcxAppUser.getVipFlag().equals("1") && DateUtil.compare(hcxAppUser.getVipTime(), new Date()) >= 0) {

            String xicheka = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.hcx_carwash_price);
            String nongchanpin = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.hcx_agriculture_price);

            // 余额增加100
            hcxAppUser.setBalancePrice(hcxAppUser.getBalancePrice().add(new BigDecimal(xicheka)).setScale(2, BigDecimal.ROUND_HALF_UP));
            // 农产品余额增加50
            hcxAppUser.setFramPrice(hcxAppUser.getFramPrice().add(new BigDecimal(nongchanpin)).setScale(2, BigDecimal.ROUND_HALF_UP));
            hcxAppUserMapper.updateById(hcxAppUser);

            // 保存账单明细给奖励人
            List<HcxWithdrawDetail> hcxWithdrawDetails = new ArrayList<>();
            for (int i = 0; i < 2; i++) {
                HcxWithdrawDetail hcxWithdrawDetail = new HcxWithdrawDetail();
                hcxWithdrawDetail.setUserId(hcxAppUser.getId());
                if (i == 0) {
                    // 余额账单
                    hcxWithdrawDetail.setDetailType(Constants.TWO);
                    hcxWithdrawDetail.setAmount(new BigDecimal(100));
                } else {
                    // 农产品账单
                    hcxWithdrawDetail.setDetailType(Constants.THREE);
                    hcxWithdrawDetail.setAmount(new BigDecimal(50));
                }
                hcxWithdrawDetail.setPhonenumber(hcxAppUser.getPhonenumber());
                hcxWithdrawDetail.setRealName(hcxAppUser.getRealName());
                // 谁给我贡献的
                hcxWithdrawDetail.setShareUserId(shareUser.getId());
                hcxWithdrawDetail.setCreateBy("admin");
                hcxWithdrawDetails.add(hcxWithdrawDetail);
            }
            hcxWithdrawDetailMapper.insertAll(hcxWithdrawDetails);

        }else if(hcxAppUser.getVipFlag().equals(VipFlagEnum.ISVIP.getValue()) && DateUtil.compare(hcxAppUser.getVipTime(), new Date()) < 0){
            // vip过期了 则把用户变为非会员
            hcxAppUser.setVipFlag(VipFlagEnum.NOVIP.getValue());
            hcxAppUser.setVipTime(null);
            hcxAppUserMapper.updateById(hcxAppUser);

        }
    }

    /**
     * @description: 10快的分佣
     * @author: kubilewang
     * @Return: void
     **/
    private void shikuai(HcxAppUser hcxAppUser, HcxAppUser shareUser) {

        // 判斷用戶是不是Vip并且在有效期内
        if (hcxAppUser.getVipFlag().equals(VipFlagEnum.ISVIP.getValue()) && DateUtil.compare(hcxAppUser.getVipTime(), new Date()) >= 0) {

            // 推广单价
            String tuiguangPrice = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.TUIGUANGDANJIAN);
            AssertUtils.isNotBlank(tuiguangPrice, "请先去系统参数中设置推广奖金额");


            hcxAppUser.setSharePrice(hcxAppUser.getSharePrice().add(new BigDecimal(tuiguangPrice)).setScale(2, BigDecimal.ROUND_HALF_UP));
            // 下线前两个人分区人数+1
            hcxAppUser.setTwoNum(hcxAppUser.getTwoNum() + 1);
            hcxAppUserMapper.updateById(hcxAppUser);

            // 记录推广奖账单
            HcxWithdrawDetail hcxWithdrawDetail = new HcxWithdrawDetail();
            hcxWithdrawDetail.setUserId(hcxAppUser.getId());
            hcxWithdrawDetail.setRealName(hcxAppUser.getRealName());
            hcxWithdrawDetail.setDetailType(Constants.FOUR);
            hcxWithdrawDetail.setAmount(new BigDecimal(tuiguangPrice));
            hcxWithdrawDetail.setPhonenumber(hcxAppUser.getPhonenumber());
            // 谁给我贡献的
            hcxWithdrawDetail.setShareUserId(shareUser.getId());
            hcxWithdrawDetail.setCreateBy("admin");
            withdrawDetailMapper.insert(hcxWithdrawDetail);

        }else if(hcxAppUser.getVipFlag().equals(VipFlagEnum.ISVIP.getValue()) && DateUtil.compare(hcxAppUser.getVipTime(), new Date()) < 0){
            // vip过期了 则把用户变为非会员
            hcxAppUser.setVipFlag(VipFlagEnum.NOVIP.getValue());
            hcxAppUser.setVipTime(null);
            hcxAppUserMapper.updateById(hcxAppUser);

        }
    }

    // 记录平台收益
    private void pingtaiShi(HcxMerchantOrder hcxMerchantOrder) {
        log.info("我来记录平台收入了{}",hcxMerchantOrder.getId());

        // 平台只会邀请这一个人 所以这个10块给到平台
        String tuiguangjiang = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.TUIGUANGDANJIAN);

        HcxPlatformProfit hcxPlatformProfit = new HcxPlatformProfit();
        hcxPlatformProfit.setOrderId(hcxMerchantOrder.getId());
        hcxPlatformProfit.setOrderNum(hcxMerchantOrder.getOrderNum());
        hcxPlatformProfit.setPrice(new BigDecimal(tuiguangjiang));
        hcxPlatformProfit.setMerchantName(hcxMerchantOrder.getMerchantName());
        hcxPlatformProfit.setProductId(hcxMerchantOrder.getProductId());
        hcxPlatformProfit.setProductName(hcxMerchantOrder.getProductName());
        hcxPlatformProfit.setDetailedType(DetailedTypeEnum.GMXCKDLDSR.getValue());
        hcxPlatformProfit.setPlatformUserId(Long.valueOf(1));
        hcxPlatformProfit.setCreateBy("admin");
        hcxPlatformProfitMapper.insert(hcxPlatformProfit);


        // 平台账号余额增加
        HcxPlatformUser hcxPlatformUser = hcxPlatformUserMapper.selectById(1);
        hcxPlatformUser.setBalance(hcxPlatformUser.getBalance().add(new BigDecimal(tuiguangjiang)));
        hcxPlatformUserMapper.updateById(hcxPlatformUser);

    }

    // 记录平台收益
    private void pingtaiYbw(HcxMerchantOrder hcxMerchantOrder) {
        log.info("我来记录平台收入了{}",hcxMerchantOrder.getId());


        // 记录平台收入的100和50
        String yibai = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.hcx_carwash_price);
        String wushi = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.hcx_agriculture_price);


        for (int i = 0; i < 2; i++) {

            HcxPlatformProfit hcxPlatformProfit = new HcxPlatformProfit();
            hcxPlatformProfit.setOrderId(hcxMerchantOrder.getId());
            hcxPlatformProfit.setOrderNum(hcxMerchantOrder.getOrderNum());
            if(i==0){
                hcxPlatformProfit.setPrice(new BigDecimal(yibai));
            }else{
                hcxPlatformProfit.setPrice(new BigDecimal(wushi));
            }
            hcxPlatformProfit.setMerchantName(hcxMerchantOrder.getMerchantName());
            hcxPlatformProfit.setProductId(hcxMerchantOrder.getProductId());
            hcxPlatformProfit.setProductName(hcxMerchantOrder.getProductName());
            hcxPlatformProfit.setDetailedType(DetailedTypeEnum.GMXCKDLDSR.getValue());
            hcxPlatformProfit.setPlatformUserId(Long.valueOf(1));
            hcxPlatformProfit.setCreateBy("admin");
            hcxPlatformProfitMapper.insert(hcxPlatformProfit);
        }


        // 平台账号余额增加
        HcxPlatformUser hcxPlatformUser = hcxPlatformUserMapper.selectById(1);
        hcxPlatformUser.setBalance(hcxPlatformUser.getBalance().add(new BigDecimal(yibai)).add(new BigDecimal(wushi)));
        hcxPlatformUserMapper.updateById(hcxPlatformUser);

    }
}
